
var pageBean = null;
var provinces = {};
var cities = {};
var spaceStatus = {};
var spaces = {};

$(document).ready(function(e) {
	 $(".select1").uedSelect({
			width : 345			  
	});
	$(".select2").uedSelect({
		width : 167  
	});
	$(".select3").uedSelect({
		width : 100
	});		

	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#add").click(add);
	$("input[type='file'][name='file']").change(uploadSpaceImage);
	$("INPUT[name='clearButton']").hide();
	$("INPUT[name='clearButton']").click(clearSpaceImage);
	initialPlaces();
	initialSpaceStatus();
	$("SELECT[name='placeProvinceSelect']").change(provinceChange);	
	search(1);	 
});


function getRequestJson(space){	
	if(space == null){
		space = {};
	}
	
	var spaceName = $.trim($("input[name='spaceName']").val());
	if(spaceName == ''){
		alert("请输入空间名称！");
		return false;
	}
	space["spaceName"] = spaceName;
	
	var spaceStatusId = $("#addSpaceStatus").val();
	if(spaceStatusId == '-1'){
		alert("请选择空间运行状态！");
		return false;
	}
	space["spaceStatus"] = spaceStatus[spaceStatusId];
	
	
	var provinceId = $("#addProvince").val();
	if(provinceId == '0'){
		alert("请选择省份！");
		return false;
	}
	space["province"] = provinces[provinceId];
	
	
	var cityId = $("#addCity").val();
	if(cityId == '0'){
		alert("请选择城市！");
		return false;
	}
	space["city"] = cities[cityId];
	
	
	var address = $.trim($("input[name='address']").val());
	if(address == ''){
		alert("请输入空间地址！");
		return false;
	}
	space["address"] = address;
	
	var postalCode = $("input[name='postalCode']").val();
	space["postalCode"] = postalCode;
	
	var spaceArea = $.trim($("input[name='spaceArea']").val());
	if(spaceArea == ''){
		spaceArea = 0;
		alert("请输入营业面积！");
		return false;
	}
	space["spaceArea"] = spaceArea;
	
	var seatCount = $.trim($("input[name='seatCount']").val());
	space["seatCount"] = seatCount;		
	
	var contactNumber = $.trim($("input[name='contactNumber']").val());
	if(contactNumber == ''){
		alert("请输入联系电话");
		return false;
	}
	space["contactNumber"] = contactNumber;
	
	var displayPicture = $.trim($("input[name='displayPicture']").val());
	if(displayPicture == ''){
		alert("请上传展示图片");
		return false;
	}
	space["displayPicture"] = displayPicture;
	
	var displayPicture2 = $.trim($("input[name='displayPicture2']").val());
//	if(displayPicture2 == ''){
//		alert("请上传展示图片");
//		return false;
//	}
	space["displayPicture2"] = displayPicture2;

	
	var displayPicture3 = $.trim($("input[name='displayPicture3']").val());
//	if(displayPicture3 == ''){
//		alert("请上传展示图片");
//		return false;
//	}
	space["displayPicture3"] = displayPicture3;


	
	var introduction = $.trim($("textarea[name='introduction']").val());
	if(introduction == ''){
		alert("请输入空间简介");
		return false;
	}
	space["introduction"] = introduction;
	
	var otherFacilities = $.trim($("input[name='otherFacilities']").val());
	if(otherFacilities == ''){
		alert("请输入配套设施");
		return false;
	}
	space["otherFacilities"] = otherFacilities;
	
	return space;
}

function clearSpaceImage(){
	var picIndex = $(this).attr("index");
	$("#uploadFile"+picIndex).val('');
	$("#spaceImage"+picIndex).prop("src",'');
	$("input[name='displayPicture" + picIndex + "']").val('');
	$(this).hide();
}


function uploadSpaceImage(){
	var picIndex = $.trim($(this).attr('pic'));
	var fileName = $(this).val();

	var dom = document.getElementById("uploadFile"+picIndex);
	var fileSize = dom.files[0].size;
	if (fileSize > 10000000) {
		alert("上传文件过大,请上传小于10M的图片");
		$(this).val("");
		return false;
	}
	var fileType = fileName.substring(fileName.lastIndexOf('.') + 1,fileName.length).toLocaleLowerCase();
	if (fileType != 'jpg' && fileType != 'bmp' && fileType != 'png' && fileType != 'gif' && fileType != "jpeg") {
		alert("图片只能上传JPG,JPEG,BMP,PNG,GIF格式的图片！");
		$(this).val("");
		return false;
	}

	
	var accessToken = localStorage.getItem('accessToken');
	$('#spaceImageForm'+picIndex).ajaxSubmit({
		dataType : "json",
		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
		beforeSubmit : function(request) { 
			//console.log("开始上传"); 
		}, 
		success : function(result, textStatus, response) { 
			console.log(JSON.stringify(result));
			$("#spaceImage" + picIndex).prop("src",result.fileUrl);
			$("input[name='displayPicture" + picIndex + "']").val(result.fileUrl);
			if($.trim(result.fileUrl) != ''){
				$("INPUT[name='clearButton'][index='" + picIndex + "']").show();
			}else{
				$("INPUT[name='clearButton'][index='" + picIndex + "']").hide();
			}
			console.log('成功上传！'); 		 
		},
		error : function(result) {
			console.log('上传失败！'); 
		} 
	});
}

function save(){	

	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/space/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='spaceList']").show();
        	$("DIV[name='spaceAdd']").hide();
        	search(pageBean.currentPage);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function update(space){
	if(space == null){
		return false;
	}
	space = getRequestJson(space);
	if(space == false){
		return false;
	}
	
	
	$.ajax({
        url: '/euc/space/update',
        data:JSON.stringify(space),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='spaceList']").show();
        	$("DIV[name='spaceAdd']").hide();
        	search(pageBean.currentPage);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function deleteData(id){
	 if(confirm("确定删除该空间?")){
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/space/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	var cur = $('.paginItem.current').find("a").html();
				cur = parseInt(cur);
				search(cur);
				alert(result.message);
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function cancle(){
	$("DIV[name='spaceList']").show();
	$("DIV[name='spaceAdd']").hide();
}

function clearSpace(){
	$("input[name='spaceName']").val('');
	$("#addSpaceStatus").val('-1').trigger("change");
	$("#addProvince").val('0').trigger('change');
	$("#addCity").val('0').trigger('change');	
	$("input[name='address']").val('');	
	$("input[name='postalCode']").val('');	
	$("input[name='spaceArea']").val('');
	$("input[name='seatCount']").val('');
	$("input[name='contactNumber']").val('');
	$("#spaceImage").prop("src",'images/img07.png');
	$("input[name='displayPicture']").val('');	
	
	$("#spaceImage2").prop("src",'images/img07.png');
	$("input[name='displayPicture2']").val('');
	
	$("#spaceImage3").prop("src",'images/img07.png');
	$("input[name='displayPicture3']").val('');	
	
	$("input[name='file']").val('');	
	$("INPUT[name='clearButton']").hide();
	$("textarea[name='introduction']").val('');
	$("INPUT[name='otherFacilities']").val('');
	/*$("select[name='spaceStatusSelect']").val('-1');*/

}

function setSpace(space){
	$("input[name='spaceName']").val(space.spaceName);
	$('#addSpaceStatus').val(space.spaceStatus.statusId).trigger('change');
	$('#addProvince').val(space.province.provinceId).trigger('change');
	$("#addCity").val(space.city.cityId).trigger('change');	
	$("input[name='address']").val(space.address);	
	$("input[name='postalCode']").val(space.postalCode);	
	$("input[name='spaceArea']").val(space.spaceArea);
	$("input[name='seatCount']").val(space.seatCount);
	$("input[name='contactNumber']").val(space.contactNumber);
	$("#spaceImage").prop("src",space.displayPicture);
	$("input[name='displayPicture']").val(space.displayPicture);
	
	$("INPUT[name='clearButton']").hide();
	if($.trim(space.displayPicture2) != ''){
		$("#spaceImage2").prop("src",space.displayPicture2);
		$("input[name='displayPicture2']").val(space.displayPicture2);
		$("INPUT[name='clearButton'][index='2']").show();
	}else{
		$("#spaceImage2").prop("src",'');
		$("input[name='displayPicture2']").val('');
	}
	
	if($.trim(space.displayPicture3) != ''){
		$("#spaceImage3").prop("src",space.displayPicture3);
		$("input[name='displayPicture3']").val(space.displayPicture3);
		$("INPUT[name='clearButton'][index='3']").show();
	}else{
		$("#spaceImage3").prop("src",'');
		$("input[name='displayPicture3']").val('');
	}
	
	$("input[name='file']").val('');	
	$("textarea[name='introduction']").val(space.introduction);
	$("INPUT[name='otherFacilities']").val(space.otherFacilities);
}

function add(){
	$("#operator").html("添加");
	clearSpace();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='spaceList']").hide();
	$("DIV[name='spaceAdd']").show();
}


function detail(id){
	var currentSpace = spaces[id];
	clearSpace();
	setSpace(currentSpace);
	$("#operator").html("编辑");
	$("DIV[name='spaceList']").hide();
	$("DIV[name='spaceAdd']").show();	
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		currentSpace = spaces[id];
		update(currentSpace);
	});
}


function search(currentPage){
	
	var parameter = $("INPUT[name='parameter']").val();
	var provinceName = $("#searchProvince").val();
	var city = $("#searchCity").val();
	var spaceStatus = $("#searchSpaceStatus").val();
	provinceName = provinceName == '0'?'':provinceName;
	city = city == '0'?'':city;
	spaceStatus = spaceStatus == '0'?'':spaceStatus;
	var requestJson = {currentPage:currentPage,data:{like:{spaceName:parameter},equals:{'province.provinceId':provinceName,'city.cityId':city,'spaceStatus.statusId':spaceStatus}}};
		
	$.ajax({
        url: '/euc/space/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		//alert(JSON.stringify(data));
        		var html = '<tr>';
        		html += '<td style="width:70px;">' + (i+1) + '</td>';
        		html += '<td style="width:160px;">' + data.spaceName + '</td>';
        		html += '<td>' + data.province.provinceName + '</td>';
        		html += '<td>' + data.city.cityName + '</td>';
        		html += '<td>' + data.spaceStatus.statusName + '</td>';
        		html += '<td>' + data.spaceArea + '</td>';
        		html += '<td>' + data.seatCount + '</td>';
        		html += '<td>' + data.seatUsedCount + '</td>';
        		html += '<td>' + data.meetingroomCount + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteData('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	spaces[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');
        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function initialPlaces(){
	$.ajax({
        url: '/euc/space/province',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	var provinceSelect = $("SELECT[name='placeProvinceSelect']");        	
        	$.each(result,function(index,data){	
           		$('<option value="'+ data.provinceId +'">'+ data.provinceName +'</option>').appendTo($(provinceSelect));
           		provinces[data.provinceId] = data;
           		var citiesSelect = $("SELECT[name='placeCitySelect']");
           		$.each(data.cities,function(index,city){	
    	       		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
    	       		cities[city.cityId] = city;	
    			});
   			});	    	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function initialSpaceStatus(){
	$.ajax({
        url: '/euc/space/status',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	var spaceStatusSelect = $("SELECT[name='spaceStatusSelect']");        	
        	$.each(result,function(index,data){	
           		$('<option value="'+ data.statusId +'">'+ data.statusName +'</option>').appendTo($(spaceStatusSelect));
           		spaceStatus[data.statusId] = data;
   			});	    	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function provinceChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var citiesSelect = $("SELECT[name='placeCitySelect']");
	$(citiesSelect).empty();		
	$('<option value="0" selected>请选择</option>').appendTo($(citiesSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(citiesSelect));
		});
	}else{			
		var citiesSelect = $("SELECT[name='placeCitySelect']");
   		$.each(cities,function(index,city){	
       		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
		});
	}
}

function initailPageNumber(totalPage,currentPage,pageLength){				
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}